#include <log.h>

#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>

#include <constants.h>
#include <lock.h>

void LogError(char* message, int exitStatus){
	LogAppend("EE", message);
	exit(exitStatus);
}

void LogWarning(char* message){
	LogAppend("WW", message);
	return;
}

void LogInfo(char* message){
	LogAppend("II", message);
	return;
}

void LogRedirect(char* fileName){
	int fd=open(fileName, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if(fd<0){
		LogWarning("Impossible d'ouvrir le fichier de Log");
		return;
	}
	
	dup2(fd, 1);
	close(fd);
	return;
}

void LogAppend(char* type, char* message){

	char ret[1024];

	time_t ctime = time(0);
  	strftime (ret,1024,"%d/%m/%y - %X (",localtime(&ctime));
	strcat(ret, type);
	strcat(ret, ") ");
	strcat(ret, message);
	puts(ret);
	fflush(stdout);

	return;
}

char dateTime[64] = "";

char* GetDateTime(){
	time_t ctime = time(0);
  	strftime (dateTime,1024,"%d/%m/%y - %X",localtime(&ctime));

	return dateTime;
}
